﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using EzyGoEzySystem.Models;
using EzyGoEzySystem.Services;
using System.Web.Security;

namespace EzyGoEzySystem.Controllers
{
    public class LoginController : Controller
    {
        EzyGoEzyDBContext dbContext = new EzyGoEzyDBContext();

        //
        // GET: /Login/

        public ActionResult Index()
        {
            return View();
        }

        //
        // POST: /Account/LogOn

        [HttpPost]
        public ActionResult Index(LoginModel account, string returnUrl)
        {
            if (ModelState.IsValid)
            {
                // check if the account already exists
                if (DataAccess.IsUserExisted(account.Username, account.Password))
                {
                    Session["LoginInfo"] = account;
                    Session["Account"] = DataAccess.GetAccount(account.Username);
                    //Session["AccountID"] = account.ID;
                    //HttpContext.Current.Session["Name"] = "An";
                    ViewBag.UserName = account.Username;
                    FormsAuthentication.SetAuthCookie(account.Username, account.RememberMe);
                    if (Url.IsLocalUrl(returnUrl) && returnUrl.Length > 1 && returnUrl.StartsWith("/")
                        && !returnUrl.StartsWith("//") && !returnUrl.StartsWith("/\\"))
                    {
                        return Redirect(returnUrl);
                    }
                    else
                    {
                        return RedirectToAction("Index", "Home");
                    }
                }
                else
                {
                    ModelState.AddModelError("", "The user name or password provided is incorrect.");
                }
            }

            return View(account);
        }

        public ActionResult LogOff()
        {
            Session["Account"] = null;
            FormsAuthentication.SignOut();
            return RedirectToAction("Index", "Home");
        }
    }
}
